package com.medical.controller;

import com.medical.domain.LoginUserVO;
import com.medical.domain.R;
import com.medical.enums.ResultCode;
import com.medical.enums.TimeEnum;
import com.medical.exception.BusinessException;
import com.medical.model.dto.LoginDto;
import com.medical.service.ILoginService;
import com.medical.utils.CaptchaUtil;
import com.medical.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2024/6/25 22:47
 * @desc 登录控制器
 */
@RestController
@Slf4j
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaUtil captchaUtil;

    /**
     * 获取验证码图片和唯一标识 key
     */
    @GetMapping("/captcha")
    public R<String> getCaptcha() {
        String code = captchaUtil.generateCaptchaText();
        String key = UUID.randomUUID().toString(); // 唯一标识
        BufferedImage image = captchaUtil.generateCaptchaImage(code);

        // 存入 Redis，5 分钟过期
        redisService.setCacheObject("captcha:" + key, code, TimeEnum.FIVE_MINUTE);

        // 返回 Base64 图片数据
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            return R.fail(1001, "生成验证码失败");
        }

        String base64Img = Base64.getEncoder().encodeToString(os.toByteArray());
        return R.ok("data:image/png;base64," + base64Img,key);
    }

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public R<LoginUserVO> login(@RequestBody LoginDto dto) {
        log.info("验证码：{}", dto.getCode());
        log.info("验证码 key：{}", dto.getCodeKey());
        String storedCode = redisService.getCacheObject("captcha:" + dto.getCodeKey(), String.class);

        if (storedCode == null || !storedCode.equalsIgnoreCase(dto.getCode())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED);
        }

        return R.ok(loginService.login(dto));
    }
}